import { Injectable } from '@angular/core';
import { MaterialSummary, ProductSummary } from '../type';

@Injectable({
  providedIn: 'root'
})
export class TcService {

  private baseUrl = "/tc-db-service/query/plm/";

  constructor() { }

  async getLatestProductSummary(filter = '') {
    if (!filter)
      filter = 'rank_desc = 1';
    else
      filter = `rank_desc = 1 and (${filter})`;

    let summaries = await this.getProductSummary(filter);
    return summaries;
  }

  /** 获取最新的物料汇总 */
  async getLatestMaterialSummary(filter = '') {
    if (!filter)
      filter = `and rank_desc = 1`;
    else
      filter = `and rank_desc = 1 and (${filter})`;

    let summaries = await this.getMaterialSummary(filter);
    return summaries;
  }

  // async getHistoryProductSummary(itemIds: string[]): Promise<ProductSummary[]> {
  //   if (itemIds.length == 0)
  //     return [];

  //   let ids = itemIds.map(id => `'${id}'`).join(',');
  //   let filter = `rank_desc <> 1 and item_id in (${ids})`;
  //   return this.getProductSummary(filter);
  // }

  // async getHistoryMaterialSummary(itemIds: string[]): Promise<MaterialSummary[]> {
  //   if (itemIds.length == 0)
  //     return [];

  //   let ids = itemIds.map(id => `'${id}'`).join(',');
  //   let filter = `rank_desc <> 1 and item_id in (${ids})`;
  //   return this.getMaterialSummary(filter);
  // }

  async searchProductSummary(searchText: string, fields: (keyof ProductSummary)[]) {
    if (!searchText)
      return this.getLatestProductSummary();

    // 大类、备案项目名称、用途、最终成品编码、成品尺寸
    // let fields: (keyof ProductSummary)[] = ['big_classname', 'project_name', 'usage', 'projectcode_id_last', 'project_size_yc'];
    let filter = fields.map(f => `${f} like '%${searchText}%'`).join(' or ');
    return this.getLatestProductSummary(filter);
  }

  async searchMaterialSummary(searchText: string, fields: (keyof MaterialSummary)[]) {
    if (!searchText)
      return this.getLatestMaterialSummary();

    // 大类、备案项目名称、用途、最终成品编码、成品尺寸
    // let fields: (keyof ProductSummary)[] = ['big_classname', 'project_name', 'usage', 'projectcode_id_last', 'project_size_yc'];
    let filter = fields.map(f => `${f} like '%${searchText}%'`).join(' or ');
    return this.getLatestMaterialSummary(filter);
  }

  private async getProductSummary(filter: string): Promise<ProductSummary[]> {
    let r = await getJSON<ProductSummary[]>(this.baseUrl + 'get_customrecreqrevision?filter=' + encodeURIComponent(filter));
    let dateFields: (keyof ProductSummary)[] = ['creation_date', 'date_released', 'last_mod_date'];
    r.forEach(dataItem => {
      dateFields.forEach(dateField => {
        let value = dataItem[dateField];
        if (!value || typeof value != "string")
          return;

        (dataItem as any)[dateField] = new Date(value).toLocaleString();
      })

    })
    return r;
  }

  private async getMaterialSummary(filter: string): Promise<MaterialSummary[]> {
    let r = await getJSON<MaterialSummary[]>(this.baseUrl + 'get_material_summary?filter=' + encodeURIComponent(filter));
    let dateFields: (keyof MaterialSummary)[] = ['creation_date', 'date_released', 'last_mod_date'];
    r.forEach(dataItem => {
      dateFields.forEach(dateField => {
        let value = dataItem[dateField];
        if (!value || typeof value != "string")
          return;

        (dataItem as any)[dateField] = new Date(value).toLocaleString();
      })

    })
    return r;
  }
}

/** 海关备案产品服务 */
@Injectable({
  providedIn: 'root'
})
export class ProductSummaryService {
  #baseUrl = "/tc-db-service/query/plm/";
  #filter: string = '';

  constructor() { }

  get filter() {
    return this.#filter;
  }

  async getLatestProductSummary(filter = '') {
    if (!filter)
      filter = 'rank_desc = 1';
    else
      filter = `rank_desc = 1 and (${filter})`;

    let summaries = await this.getProductSummary(filter);
    return summaries;
  }


  async getHistoryProductSummary(itemIds: string[]): Promise<ProductSummary[]> {
    if (itemIds.length == 0)
      return [];

    let ids = itemIds.map(id => `'${id}'`).join(',');
    let filter = `rank_desc <> 1 and item_id in (${ids})`;
    return this.getProductSummary(filter);
  }



  async searchProductSummary(searchText: string, fields: (keyof ProductSummary)[]) {
    if (!searchText)
      return this.getLatestProductSummary();

    // 大类、备案项目名称、用途、最终成品编码、成品尺寸
    // let fields: (keyof ProductSummary)[] = ['big_classname', 'project_name', 'usage', 'projectcode_id_last', 'project_size_yc'];
    let filter = fields.map(f => `${f} like '%${searchText}%'`).join(' or ');
    return this.getLatestProductSummary(filter);
  }

  private async getProductSummary(filter: string): Promise<ProductSummary[]> {
    this.#filter = filter;
    let r = await getJSON<ProductSummary[]>(this.#baseUrl + 'get_customrecreqrevision?filter=' + encodeURIComponent(filter));
    let dateFields: (keyof ProductSummary)[] = ['creation_date', 'date_released', 'last_mod_date'];
    r.forEach(dataItem => {
      dateFields.forEach(dateField => {
        let value = dataItem[dateField];
        if (!value || typeof value != "string")
          return;

        (dataItem as any)[dateField] = new Date(value).toLocaleString();
      })

    })
    return r;
  }


}

/** 海关备案物料服务 */
@Injectable({
  providedIn: 'root'
})
export class MaterialSummaryService {
  #baseUrl = "/tc-db-service/query/plm/";
  #filter: string = '';

  constructor() { }

  get filter() {
    return this.#filter;
  }

  /** 获取最新的物料汇总 */
  async getLatestMaterialSummary(filter = '') {
    if (!filter)
      filter = `rank_desc = 1`;
    else
      filter = `rank_desc = 1 and (${filter})`;

    let summaries = await this.getMaterialSummary(filter);
    return summaries;
  }

  async getHistoryMaterialSummary(itemIds: string[]): Promise<MaterialSummary[]> {
    if (itemIds.length == 0)
      return [];

    let ids = itemIds.map(id => `'${id}'`).join(',');
    let filter = `rank_desc <> 1 and item_id in (${ids})`;
    return this.getMaterialSummary(filter);
  }

  async searchMaterialSummary(searchText: string, fields: (keyof MaterialSummary)[]) {
    if (!searchText)
      return this.getLatestMaterialSummary();

    // 大类、备案项目名称、用途、最终成品编码、成品尺寸
    // let fields: (keyof ProductSummary)[] = ['big_classname', 'project_name', 'usage', 'projectcode_id_last', 'project_size_yc'];
    let filter = fields.map(f => `${f} like '%${searchText}%'`).join(' or ');
    return this.getLatestMaterialSummary(filter);
  }


  private async getMaterialSummary(filter: string): Promise<MaterialSummary[]> {
    this.#filter = filter;
    let r = await getJSON<MaterialSummary[]>(this.#baseUrl + 'get_material_summary?filter=' + encodeURIComponent(filter));
    let dateFields: (keyof MaterialSummary)[] = ['creation_date', 'date_released', 'last_mod_date'];
    r.forEach(dataItem => {
      dateFields.forEach(dateField => {
        let value = dataItem[dateField];
        if (!value || typeof value != "string")
          return;

        (dataItem as any)[dateField] = new Date(value).toLocaleString();
      })

    })
    return r;
  }
}

async function getJSON<T>(url: string) {
  let r = await fetch(url);
  let text = await r.text();
  if (r.status != 200) {
    throw new Error(text);
  }
  let j = JSON.parse(text);
  return j as T;
}
